<script setup>
import * as echarts from 'echarts';
const orderData = ref({});
const selected = ref('LAST_7_DAYS');
const timeValue = ref();
const formData = inject('formData');
const chartRef = ref();
let chart;
let resizeObserver;
const loading = ref(true);
const options = [
  { label: '前7天', value: 'LAST_7_DAYS' },
  { label: '前30天', value: 'LAST_30_DAYS' },
  { label: '上月', value: 'LAST_MONTH' },
  { label: '自定义', value: 'CUSTOM' }
];
//  获取订单销售数据
const getOrderData = async () => {
  loading.value = true;
  loading.value = false;
};
//切换类型
const handleSwitch = async (item) => {
  item.value == 'CUSTOM' ? (timeValue.value = getLastThreeMonthsTimeRange()) : (timeValue.value = []);
  selected.value = item.value;
  await getOrderData();
  updateChart();
};
// 时间选择
const handleDateChange = async () => {
  await getOrderData();
  updateChart();
};
const updateChart = () => {
  if (!chart) return;
  const xData = orderData.value.x || [];
  const yData = orderData.value.y || [];
  const saleCountData = yData.find((item) => item.name === 'saleCount')?.data || [];
  const amountData = yData.find((item) => item.name === 'amount')?.data || [];
  const quantityData = yData.find((item) => item.name === 'quantity')?.data || [];
  const option = {
    xAxis: { data: xData },
    series: [
      { name: '订单数量', data: saleCountData },
      { name: '销售金额', data: amountData },
      { name: '商品销量', data: quantityData }
    ]
  };
  chart.setOption(option);
};
onMounted(async () => {
  await getOrderData();
  chart = echarts.init(chartRef.value);
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      top: '0%',
      data: ['订单数量', '销售金额', '商品销量'],
      textStyle: {
        fontSize: 16
      }
    },
    grid: {
      left: '5%',
      right: '2%',
      bottom: '5%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      show: true,
      boundaryGap: false,
      data: orderData.value?.x,
      splitLine: {
        show: true,
        lineStyle: { type: 'dashed', color: '#e0e0e0' }
      },
      axisLine: {
        lineStyle: { type: 'solid', color: '#ccc' }
      }
    },
    yAxis: [
      {
        type: 'value',
        position: 'left',
        offset: 0,
        axisLine: {
          lineStyle: { color: '#32CD32' }
        },
        axisLabel: {
          formatter: '{value}',
          fontSize: 10
        }
      },
      {
        type: 'value',
        position: 'left',
        offset: 50,
        axisLine: {
          lineStyle: { color: '#FFA500' }
        },
        axisLabel: {
          formatter: '${value}',
          fontSize: 10
        }
      },
      {
        type: 'value',
        position: 'right',
        axisLine: {
          lineStyle: { color: '#5b95f8' }
        },
        axisLabel: {
          formatter: '{value}',
          fontSize: 10
        }
      }
    ],
    series: [
      {
        name: '订单数量',
        type: 'line',
        yAxisIndex: 0,
        smooth: true,
        data: orderData.value.y?.find((item) => item.name === 'saleCount')?.data || [],
        lineStyle: { color: '#32CD32' },
        itemStyle: { color: '#32CD32' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(50, 205, 50, 0.4)' },
              { offset: 1, color: 'rgba(255, 255, 255, 0)' }
            ]
          }
        }
      },
      {
        name: '销售金额',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        data: orderData.value.y?.find((item) => item.name === 'amount')?.data || [],
        lineStyle: { color: '#FFA500' },
        itemStyle: { color: '#FFA500' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(255, 165, 0, 0.4)' },
              { offset: 1, color: 'rgba(255, 255, 255, 0)' }
            ]
          }
        }
      },
      {
        name: '商品销量',
        type: 'line',
        yAxisIndex: 2,
        smooth: true,
        data: orderData.value.y?.find((item) => item.name === 'quantity')?.data || [],
        lineStyle: { color: '#5b95f8' },
        itemStyle: { color: '#5b95f8' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(91, 149, 248, 0.4)' },
              { offset: 1, color: 'rgba(255, 255, 255, 0)' }
            ]
          }
        }
      }
    ]
  };

  chart.setOption(option);

  //  自动监听容器大小变化，触发图表 resize
  resizeObserver = new ResizeObserver(() => {
    chart.resize();
  });
  resizeObserver.observe(chartRef.value);
});

onBeforeUnmount(() => {
  chart?.dispose();
  resizeObserver?.disconnect();
});
</script>

<template>
  <ElCard class="rd-8px shadow-sm">
    <div class="h-[360px]">
      <div class="flex items-center justify-between pb-[16px]">
        <div class="flex items-end">
          <div class="text-[16px] font-bold">订单销售</div>
        </div>
        <div class="flex items-center">
          <div class="button-group">
            <div v-for="item in options" :key="item.value" class="btn" :class="{ selected: item.value === selected }" @click="handleSwitch(item)">
              {{ item.label }}
            </div>
          </div>
          <el-date-picker
            v-if="selected == 'CUSTOM'"
            v-model="timeValue"
            style="margin-left: 10px; width: 250px !important"
            type="daterange"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            range-separator="-"
            :clearable="false"
            @change="handleDateChange"
          />
        </div>
      </div>
      <div ref="chartRef" style="width: 100%; height: 350px" />
    </div>
  </ElCard>
</template>
<style lang="scss" scoped>
.button-group {
  display: inline-flex;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
}

.btn {
  padding: 6px 14px;
  cursor: pointer;
  user-select: none;
  font-size: 16px;
  color: #606266;
  background-color: #fff;
  border-right: 1px solid #dcdfe6;
  transition: all 0.2s;
}

.btn:first-child {
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
}

.btn:last-child {
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
  border-right: none;
}

.btn:hover {
  background-color: #f2f6fc;
}

.btn.selected {
  color: #4d6bfe;
  box-shadow: inset 0 0 0 1px #4d6bfe;
}
</style>
